import {HashRouter, Route, Routes} from "react-router-dom";
import React, {ReactElement} from "react";
import {Spin} from "antd";

const loadingComponent = () => {
    return (
        <Spin spinning={true} fullscreen />
    )
}

interface RouteConf {
    key: string | number,
    path: string,
    element: ReactElement,
    subItems: null | RouteConf[]
}

const toRouteConf = (
    key: string | number,
    path: string,
    element: ReactElement,
    subItems: null | RouteConf[]
): RouteConf => {
    return {
        key,
        path,
        element,
        subItems: subItems
    }
}

const MainPage = React.lazy(() => import("@/pages/MainPage"));
const UserPage = React.lazy(() => import("@/pages/UserPage"));
const SelfPage = React.lazy(() => import("@/pages/UserPage/SelfPage"));
const UserControlPage = React.lazy(() => import("@/pages/UserPage/UserControlPage"));
const ObjControlPage = React.lazy(() => import("@/pages/UserPage/ObjControlPage"));

const routeConf: RouteConf[] = [
    toRouteConf(
        1,
        "/",
        <MainPage/>,
        null
    ),
    toRouteConf(
        2,
        "/user",
        <UserPage/>,
        [
            toRouteConf(
                3,
                "",
                <SelfPage/>,
                null
            ),
            toRouteConf(
                4,
                "userControl",
                <UserControlPage/>,
                null
            ),
            toRouteConf(
                5,
                'objControl',
                <ObjControlPage/>,
                null
            )
        ]
    ),
]

const RouteConfToElement = (item: RouteConf) => {
    if (item == null) {
        return <></>;
    }
    return (
        <Route key={item.key}
               path={item.path}
               element={
            <React.Suspense fallback={loadingComponent()}>
                {item.element}
            </React.Suspense>
        }>
            {item.subItems == null ? <></> : item.subItems.map(RouteConfToElement)}
        </Route>
    )
}

export const AppRouter = () => {
    return (
        <HashRouter>
            <Routes>
                {
                    routeConf.map(item => RouteConfToElement(item))
                }
            </Routes>
        </HashRouter>
    )
}